﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Marmat.FrameWork
{

    /// <summary>
    /// 基于 IDocumentViewFormController 的拓展函数类。
    /// </summary>
    public static class IDocumentViewFormControllerExtensions
    {
        /// <summary>
        /// 打开编辑窗体。
        /// </summary>
        public static void ShowCreateForm<Entity, DataSource>(this Marmat.Template.WinForm.IDocumentViewFormController<Entity, DataSource> controller)
        {
            controller.Management.ShowCreateForm();
        }

        /// <summary>
        /// 打开编辑窗体。
        /// </summary>
        /// <typeparam name="Entity"></typeparam>
        /// <typeparam name="DataSource"></typeparam>
        /// <param name="controller"></param>
        /// <param name="instance">主键值</param>
        public static void ShowEditForm<Entity, DataSource>(this Marmat.Template.WinForm.IDocumentViewFormController<Entity, DataSource> controller, Entity instance)
        {
            string primaryName = controller.Management.Command.PrimaryName;
            if (instance is DataRow dataRow)
            {
                controller.Management.ShowEditForm(dataRow[primaryName]);
            }
            else
            {
                var member = instance.GetType().GetMembers().Where(x => x.Name == primaryName && (x is FieldInfo || x is PropertyInfo)).FirstOrDefault();
                if (member is FieldInfo field)
                    controller.Management.ShowEditForm(field.GetValue(instance));
                else if (member is PropertyInfo property)
                    controller.Management.ShowEditForm(property.GetValue(instance));
            }
        }

        /// <summary>
        /// 打开编辑窗体。
        /// </summary>
        /// <typeparam name="Entity"></typeparam>
        /// <typeparam name="DataSource"></typeparam>
        /// <param name="controller"></param>
        /// <param name="id">主键值</param>
        public static void ShowEditForm<Entity, DataSource>(this Marmat.Template.WinForm.IDocumentViewFormController<Entity, DataSource> controller, string id)
        {
            controller.Management.ShowEditForm(id);
        }

        /// <summary>
        /// 打开编辑窗体。
        /// </summary>
        /// <typeparam name="Entity"></typeparam>
        /// <typeparam name="DataSource"></typeparam>
        /// <param name="controller"></param>
        /// <param name="id">主键值</param>
        public static void ShowEditForm<Entity, DataSource>(this Marmat.Template.WinForm.IDocumentViewFormController<Entity, DataSource> controller, int id)
        {
            controller.Management.ShowEditForm(id);
        }
    }
}
